<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/10
 * Time: 10:11
 */

namespace app\admin\controller;

use app\admin\model\GoodsCategory as GoodsCategoryModel;
use app\admin\model\Goods as GoodsModel;
use app\admin\model\GoodsImage as GoodsImageModel;
use app\admin\model\GoodsModel as GoodsModelModel;
use app\admin\model\GoodsSpec as GoodsSpecModel;
use app\admin\model\GoodsSpecItem as GoodsSpecItemModel;
use app\admin\model\GoodsSpecPrice as GoodsSpecPriceModel;
use think\Collection;

class GoodsController extends BaseController
{
    public function index()
    {
        $map = [];
        $params = $this->request->param();
        if(!empty($params['cid'])){
            $map['category'] = $params['cid'];
        }
        $this->assign([
            'goodsCategory' => GoodsCategoryModel::all(),
            'goods'=> GoodsModel::where($map)->order(['id'=>'asc'])->paginate(8,false,['type'=>'page\Page']),
        ]);
        return $this->fetch();
    }

    public function add()
    {
        if($this->request->isGet()){
            $this->assign([
                'goodsCategory' => GoodsCategoryModel::getGoodsOrder(),
                'goodsModels' => GoodsModelModel::order(['id'=>'asc'])->select(),
            ]);
            return $this->fetch();
        }
        if($this->request->isPost()){
            $params = $this->request->param();
            if($this->request->file('cover_img')){
                $uploadFile = uploadFile('cover_img',100,100,'uploads/goods');
                $params['cover_img'] = $uploadFile['origin'];
                $params['cover_sm_img'] = $uploadFile['thumb'];
                $params['cover_img_origin'] = $uploadFile['tag'];
            }
            return json((new GoodsModel())->addGoods($params,false));
        }
        $this->error('非法操作!');
    }

    public function edi()
    {
        $params = $this->request->param();
        if($this->request->isGet()){
            $data = GoodsModel::with('goodsImage')->find($params['id']);
            $goodsSpecPrice = GoodsSpecPriceModel::where(['goods_id'=>$params['id']])->select();
            if(!empty($goodsSpecPrice)){
                $goodsSpecItemIds = [];
                foreach($goodsSpecPrice as $a=>$b){
                    $goodsSpecItemIds[$a]['spec_item_ids'] = $b->getData('spec_item_ids');
                    $goodsSpecItemIds[$a]['price'] = $b->getData('price');
                    $goodsSpecItemIds[$a]['spec_item_arr'] =explode('_',$b->getData('spec_item_ids'));
                    unset($goodsSpecItemIds[$a]['spec_item_arr'][0]);
                    foreach($goodsSpecItemIds[$a]['spec_item_arr'] as $c=>$d){
                        $goodsSpecItemIds[$a]['spec_item_names'][] = GoodsSpecItemModel::where('id','eq',$d)->find();
                    }
//                    $goodsSpecItemIds[$a]['spec_item_names'] = GoodsSpecItemModel::where('id','in',$goodsSpecItemIds[$a]['spec_item_arr'])->select();
                }
                $goodsSpec = GoodsSpecModel::where(['model_id'=>$data->getData('model_id')])->select();
                $this->assign([
                    'goodsSpec' => $goodsSpec,
                    'goodsSpecItemIds' => $goodsSpecItemIds,
                ]);
            }

            $this->assign([
                'goodsCategory' =>GoodsCategoryModel::getGoodsOrder(),
                'data' =>$data,
                'goodsModels' => GoodsModelModel::order(['id'=>'asc'])->select(),
            ]);
            return $this->fetch();
        }
        if($this->request->isPost()){
            if($this->request->file('cover_img')){
                $uploadFile = uploadFile('cover_img',100,100,'uploads/goods');
                $params['cover_img'] = $uploadFile['origin'];
                $params['cover_sm_img'] = $uploadFile['thumb'];
                $params['cover_img_origin'] = $uploadFile['tag'];
                $oldFile = GoodsModel::field('cover_img,cover_sm_img,cover_img_origin')->find($params['id']);
                uploadDelete([$oldFile->cover_img,$oldFile->cover_sm_img],$oldFile->cover_img_origin);
            }
            return json((new GoodsModel())->addGoods($params,true));
        }
        $this->error('非法操作!');
    }

    public function del()
    {
        $id = $this->request->param('id');
        $image = [];
        $good = GoodsModel::field('cover_img,cover_sm_img,cover_img_origin')->find($id);
        if($good->cover_img){
            array_push($image,[$good->cover_img,$good->cover_img_origin]);
        }
        if($good->cover_sm_img){
            array_push($image,[$good->cover_sm_img,$good->cover_img_origin]);
        }
        $goodsImage = GoodsImageModel::where('goods_id',$id)->select();
        if(!empty($goodsImage)){
            foreach($goodsImage as $k=>$v){
                array_push($image,[$v->url,$v->origin]);
            }
        }
        uploadDeleteFile($image);
        GoodsImageModel::where('goods_id','eq',$id)->delete();
        GoodsSpecPriceModel::where('goods_id','eq',$id)->delete();
        if(GoodsModel::where('id','eq',$id)->delete()){
            return ['error'=>0,'msg'=>'删除成功!'];
        }else{
            return ['error'=>1,'msg'=>'删除失败!'];
        }
    }

//    public function goodsModelDetails()
//    {
//        $model_id = $this->request->param('model_id');
//        $goodsModel = GoodsModelModel::with(['spec'=>function($query){$query->withField('id,name');},'spec.item'])->find($model_id)->toArray();
//        if(empty($goodsModel['spec'])){
//            return ['error'=>1,'msg'=>'当前模型下没有规格'];
//        }
//        $arr = [];
//        foreach($goodsModel['spec'] as $k=>$v){
//            foreach($v['item'] as $key=>$val){
//                $arr[$k][] = $val['id'];
//            }
//        }
//        $cart= $this->CartesianProduct($arr);
//        foreach($cart as $a=>$b){
//            $cart[$a] = explode('_',$b);
//        }
//
//        $item = [];
//        foreach($cart as $c=>$d){
//            foreach($d as $e=>$f){
//                $cart[$c][$e] = GoodsSpecItemModel::where('id','eq',$f)->find();
//                $item[$c][$e] = $cart[$c][$e]->name;
//            }
//        }
//        $this->assign([
//            "item" => $item,
//            "cart" => $cart,
//            "goodsModel" => $goodsModel,
//        ]);
//        return $this->fetch('spec');
//    }

    public function goodsPhotoDel()
    {
        $id = $this->request->param('id');
        $image = GoodsImageModel::field('url,origin')->find($id);
        uploadDelete([$image->url],$image->origin);
        if(GoodsImageModel::where('id','eq',$id)->delete()){
            return ['error'=>0,'msg'=>'删除成功!'];
        }else{
            return ['error'=>1,'msg'=>'删除失败!'];
        }
    }

    public function uploadReceive()
    {
        return json(uploadFile('file',null,null,'/uploads/goods_image'));
    }

    //生成笛卡尔积的方法
//    public function CartesianProduct($sets){
//        if(count($sets) == 1){
//            $result = [];
//            foreach($sets[0] as $a=>$b){
//                $result[] = '_'.$b;
//            }
//            return $result;
//        }
//
//
//        $result = array();
//        for($i=0,$count=count($sets); $i<$count-1; $i++){
//            if($i==0){
//                $result = $sets[$i];
//            }
//            $tmp = array();
//            foreach($result as $res){
//                foreach($sets[$i+1] as $set){
//                    $tmp[] = $res.'_'.$set;
//                }
//            }
//            $result = $tmp;
//        }
//        return $result;
//    }

    //改变商品上下架的情况
    public function changOnSale()
    {
        $params = $this->request->param();
        if(GoodsModel::where(['id'=>$params['id']])->update(['is_on_sale'=>$params['is_on_sale']])){
            return ['error'=>0,'msg'=>'操作成功'];
        }else{
            return ['error'=>1,'msg'=>'操作成功'];
        }
    }

    //获取单个商品的价格
    public function getGoodPrice()
    {
        $id = $this->request->param('id');
        $res = GoodsModel::field('sale_price')->where(['id'=>$id])->find();
        if($res){
            return ['error'=>0,'msg'=>$res->getData('sale_price')];
        }else{
            return ['error'=>1,'msg'=>'获取商品价格失败'];
        }
    }
}